#include "hdcamera.h"
#include "hdshareddata.h"

static int camerasCount = 0;

HDCamera::HDCamera(QObject *parent,int frameRate, int frameWidth, int frameHeight)
	: QThread(parent)
{
	_frameRate = frameRate;
	_frameWidth = frameWidth;
	_frameHeight = frameHeight;
	_pause = false;
	
	_capture = 0;

	_cameraIndex = camerasCount++;

	bInitialize = false;
	start();
}

HDCamera::~HDCamera()
{
	terminate();
	wait();
	ReleaseCapture();
}

void HDCamera::run()
{
	forever
	{
		if(_capture)
		{
			if(_pause)
			{
				captureReady[_cameraIndex]->acquire();
				captureFinished[_cameraIndex]->release();
			}
			else if (cvGrabFrame(_capture))
			{
				captureReady[_cameraIndex]->acquire();
				_frame = cvRetrieveFrame(_capture);
				captureFinished[_cameraIndex]->release();
			}
		}
		else if(bInitialize)
		{
			bInitialize = false;

			_capture = cvCreateCameraCapture(_deviceIndex + 1);

// 			if (!_capture)
// 				return Camera_Init_Failed;
// 			else
// 			{
				//NOT WORKING..Properties are not being set
				cvSetCaptureProperty(_capture, CV_CAP_PROP_FRAME_WIDTH, _frameWidth);
				cvSetCaptureProperty(_capture, CV_CAP_PROP_FRAME_HEIGHT, _frameHeight);
				cvSetCaptureProperty(_capture, CV_CAP_PROP_FPS,  _frameRate);
// 				return Camera_Init_Successful;
// 			}
		}
	}
}

/*
 *	Initialize the camera parameters
 *	Hint: It doesn't start capturing yet, call StartCapture() for start capturing.
 */
CameraInitResult HDCamera::Initialize(int deviceIndex)
{
	bInitialize = true;
	_deviceIndex = deviceIndex;
	return Camera_Init_Successful;
}

/*
 *	Start capturing from the camera.
 *	you can access the captured frame by calling frame().
 */
void HDCamera::StartCapture()
{
	start();
}

/* 
 *	Pause the capturing of the camera.
 *	Hint: Calling frame() will get you the last frame has been captured.
 */
void HDCamera::PauseCapture(bool pause)
{
	_pause = pause;
}

/*
 *	Release the capture to the system and terminate the process.
 */
void HDCamera::ReleaseCapture()
{
	cvReleaseCapture(&_capture);
	exit();
}

/*
 *	Returns the last frame captured by the camera.
 */
IplImage* HDCamera::frame()
{
	return _frame;
}

